<template>
  <p-drawer
    placement="right"
    :closable="false"
    width="calc(100vw - 200px)"
    :visible="visible"
    :mask-closable="false"
    :destroy-on-close="true"
    @close="onClose"
  >
    <TaskTitle title-name="新增商机" />
    <div class="list-container">
      <TitleSecondary title="基本信息" />
      <FormBusinessInfo
        ref="form"
        :form="form"
        :show-form="false"
        @number-click="numberInfo"
      />
      <TableBusinessStage ref="table" default-icon="up" />
      <BottomLine />
    </div>
    <ButtonGroup
      class="footer"
      :options="footerButtons"
      @click="handleButtonClick"
    />
  </p-drawer>
</template>

<script>
import FormBusinessInfo from '@/components/task/FormBusinessInfo.vue';
import DrawerMixin from './mixin';
import {
  postBusinessSave,
  postCreateOrUpdate,
  postBusinessAdd,
} from '@/api/business.js';
import TableBusinessStage from '@/components/task/TableBusinessStage.vue';

export default {
  components: {
    FormBusinessInfo,
    TableBusinessStage,
  },
  mixins: [DrawerMixin],
  data() {
    return {
      form: {
        leadsName: '',
        leadsSource: '',
        crustItemName: '',
        crustItemNo: '',
        crustItemStep: '',
        itemDemandNum: '',
        expectPrice: '',
        expectCost: '',
        expectQuantity: '',
        salesOrgCode: '',
        salesOrgName: '',
        salesGroupCode: '',
        salesGroupName: '',
        pmGroup: {
          key: '',
          label: '',
        },
        pm: {
          key: '',
          label: '',
        },
        salesOrg: {
          key: '',
          label: '',
        },
        salesGroup: {
          key: '',
          label: '',
        },
        customerName: '',
        assessLevel: '',
        customerCode: '',
        appCategory: '',
        salesAreaName: '',
        salesName: this.$store.state.user.name,
        remark: '',
        customerShortName: '',
        opportunityName: '',
        expectTime: '',
        competitor: '',
        expectShare: '',

        salesUserId: this.$store.state.user.uid,
      },
      user: this.$store.state.user.name,
      uid: this.$store.state.user.uid,
    };
  },

  computed: {
    footerButtons() {
      return [
        {
          key: 'save',
          type: 'primary',
          label: '保存',
        },
        {
          key: 'submit',
          label: '商机信息确认',
        },
        {
          key: 'close',
          label: '返回',
        },
      ];
    },
  },
  watch: {
    visible: {
      handler(val) {
        if (!val) return;
        const business = this.detail || {};
        this.form = {
          leadsName: business.leadsName || '',
          leadsNo: business.leadsNo || '',
          leadsSource: business.leadsSource || '',
          crustItemName: business.custItemName || '',
          crustItemNo: business.custItemNo || '',
          crustItemStep: business.custItemStep || '',
          itemDemandNum: business.itemDemandNum || '',
          expectPrice: business.expectPrice || '',
          expectCost: business.expectCost || '',
          expectQuantity: business.expectAmount || '',
          salesOrgCode: business.salesOrgCode || '',
          salesOrgName: business.salesOrgName || '',
          salesGroupCode: business.salesGroupCode || '',
          salesGroupName: business.salesGroupName || '',
          customerName: business.customerName || '',
          assessLevel: business.assessLevel || '',
          appCategory: business.appCategory || '',
          customerShortName: business.customerShortName || '',
          pmGroup: {
            key: business.pmGroupCode,
            label: business.pmGroupName,
          } || {
            key: '',
            label: '',
          },
          pm: {
            key: business.pmUserId,
            label: business.pmName,
          } || {
            key: '',
            label: '',
          },
          salesOrg: {
            key: business.salesOrgCode,
            label: business.salesOrgName,
          } || {
            key: '',
            label: '',
          },
          salesGroup: {
            key: business.salesGroupCode,
            label: business.salesGroupName,
          } || {
            key: '',
            label: '',
          },
          customerCode: business.customerCode || '',
          salesName: business.salesName || this.$store.state.user.name,
          remark: business.remark || '',
          salesAreaName: business.salesAreaName || '',
          updateDeptName: business.updateDeptName || '',
          opportunityName: '',
          expectTime: '',
          competitor: '',
          expectShare: '',
          salesUserId: business.salesUserId || this.$store.state.user.uid,
        };
      },
      immediate: true,
    },
  },
  created() {},
  methods: {
    onClose() {
      this.$emit('update:visible', false);
      this.$emit('fresh');
    },
    async submitData(operating) {
      const valid = await this.$refs.form.validate();
      if (!valid) return new Promise(() => {});
      // 获取流程id
      const res = await postCreateOrUpdate({
        bizModule: 'biz',
        currStatus: '2',
        bizType: '4',
      });
      const processId = res.data.data;
      const opportunityStageList = this.$refs.table.dataSource.map(item => {
        return {
          opportunityStage: item.opportunityStage,
          currentUserId: item.currentUserId,
          currentUserName: item.currentUserName,
          departmentCode: item.departmentCode,
          departmentName: item.departmentName,
          positionName: item.positionName,
          positionCode: item.positionCode,
        };
      });
      if (operating) {
        // 提交
        if (this.$refs.table.dataSource[0]['principal'].length) {
          // console.log('1');
        } else {
          this.$message.error('请先选择商机信息确认负责人');
          return;
        }
        try {
          await this.$confirm(
            '确定提交吗？提交后将进入“商机信息确认”阶段，且不能再更改商机信息'
          );
          await postBusinessAdd({
            opportunityStageList,
            ...this.form,
            processId,
            pmGroupName: this.form.pmGroup?.label,
            pmGroupCode: this.form.pmGroup?.key,
            pmUserId: this.form.pm?.key,
            pmName: this.form.pm?.label,
            attachmentId: this.$refs.form.list[this.$refs.form.list.length - 1]
              ?.id,
          });
          this.$message.success('提交成功！');
          this.closeCallback();
        } catch (error) {
          // console.log('error: ', error);
        }
      } else {
        // 保存
        if (this.$refs.table.dataSource[0]['principal'].length) {
          // console.log('1');
        } else {
          this.$message.error('请先选择商机信息确认负责人');
          return;
        }
        await postBusinessSave({
          opportunityStageList,
          ...this.form,
          processId,
          pmGroupName: this.form.pmGroup?.label,
          pmGroupCode: this.form.pmGroup?.key,
          pmUserId: this.form.pm?.key,
          pmName: this.form.pm?.label,
          attachmentId: this.$refs.form.list[this.$refs.form.list.length - 1]
            ?.id,
        });
        this.$message.success('保存成功！');
        this.closeCallback();
      }
    },
    // 提交
    async submitCallback() {
      await this.submitData(1);
    },
    // 保存
    async saveCallback() {
      await this.submitData(0);
    },
    // 返回
    closeCallback() {
      this.onClose();
    },
    handleButtonClick(key) {
      const fn = `${key}Callback`;
      this[fn] && this[fn]();
    },
    numberInfo(val) {
      this.$emit('number-click', val);
    },
  },
};
</script>

<style lang="less" scoped>
.footer {
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-top: 1px solid #e5e6e9;
}
.list-container {
  height: calc(100% - 110px);
  display: flex;
  flex-direction: column;
  overflow-y: scroll;
  position: relative;
  box-sizing: border-box;
  padding: 10px 24px;
}

/deep/ .poros-drawer-body {
  min-width: 1136px;
  height: 100%;
  padding: 0;
}
.progress-container {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
</style>
